﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Threading
{
    public static class ReaderWriterLockEx
    {
        /// <summary>
        /// 在读锁中执行任务
        /// </summary>
        /// <param name="_lock"></param>
        /// <param name="action"></param>
        public static void Reader(this ReaderWriterLock _lock, Action action)
        {
            _lock.AcquireReaderLock(Timeout.Infinite);
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            _lock.ReleaseReaderLock();
        }

        /// <summary>
        /// 在读锁中获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="_lock"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static T Reader<T>(this ReaderWriterLock _lock, Func<T> func)
        {
            _lock.AcquireReaderLock(Timeout.Infinite);
            T t = default(T);
            try
            {
                t = func();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            _lock.ReleaseReaderLock();
            return t;
        }

        /// <summary>
        /// 在写锁中处理数据
        /// </summary>
        /// <param name="_lock"></param>
        /// <param name="action"></param>
        public static void Writer(this ReaderWriterLock _lock, Action action)
        {
            _lock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            _lock.ReleaseWriterLock();
        }
    }
}
